package runtimeexec;

import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
//FIXME: Underconstruction
/**
 
 * 1.remember current directory
 * 
 * @author Ganesh
 *
 */
public class Dos {
	boolean exitOk = false;

	public Dos(){
		runDos();
	}
	public void runDos() {

		do {
			execCmd();

		} while (!exitOk);
	}

	private boolean isExitCmd(String cmd) {
		return (cmd.equalsIgnoreCase("exit"));

	}

	private String readCmd() {
		Scanner sc = new Scanner(System.in);
		return sc.nextLine();
	}

	private void execDirTest() throws Exception {
		String[] command = new String[4];
		command[0] = "cmd";
		command[1] = "/c";
		command[2] = "dir";
		command[3] = "D:\\";
		Process p = Runtime.getRuntime().exec(command);
		BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
		// read the output from the command
		String s = null;
		while ((s = stdInput.readLine()) != null) {
			System.out.println("hello" + s);
		}
	}

	private void execCmd() {

		Process p = null;
		try {
			p = Runtime.getRuntime().exec(getCorrectedCommand());
		} catch (IOException e1) {
			System.err.println("Error on Command");
			return;
		}
		BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
		// read the output from the command
		String s = null;
		try {
			while ((s = stdInput.readLine()) != null) {
				System.out.println(s);
			}
		} catch (IOException e) {
		}
	}

	/**
	 * makes String[],
	 * 
	 * @param command
	 * @return
	 */
	private String[] getCorrectedCommand() {
		String actCmd = readCmd();
		if (isExitCmd(actCmd)) {
			exitOk = true;
		}
		StringTokenizer tk = new StringTokenizer(actCmd, " ");
		int tokens = tk.countTokens();

		String[] retCommand = new String[2 + tokens];
		retCommand[0] = "cmd";
		retCommand[1] = "/c";
		int i = 0;
		while (i < tokens) {
			i++;
			retCommand[1 + i] = tk.nextToken();
			// TODO: format directory--> c:\ to c:\\,c:\ to c:\\
		}

		return retCommand;
	}
}
